#-*- coding: utf-8 -*-
'''
Created on Jun 24, 2012

@author: bbg
'''


from helper.login_session_manager import LoginSessionManager
from helper.cdkey_manager import CdkeyManager 
import dbwrapper,datetime
from dbwrapper.companyx.user_right import UserRight
from dbwrapper.company_management.company import Company
from dbwrapper.company_management.rights import Rights 
from dbwrapper.companyx.shop import Shop
from dbwrapper.companyx.login_session import LoginSession
import json
from service_base import ServiceBase 
from common.debug import Debug
import cgi
import cStringIO
import uuid

class LoginService(ServiceBase):


    def __init__(self, start_response):
        
        ServiceBase.__init__(self, start_response)
        self.debug = Debug()
    
    def application(self, params):
        '''
        login application entrance, two types:
        1. client login
        2. web login
        '''
        #params = parse(None, environ)      
                
        login_type = params.getfirst('type')
        if login_type == '0': # client login
            return self._clientLogin(params)
        elif login_type == '1': # web login
            return self._webLogin(params)
        
        return self._responseInvalidParam()
    

    def applicationget(self, params,paths):
        '''
        login application entrance, two types:
        1. client login
        2. web login
        '''
        #params = parse(None, environ)         
        client_type = params.getfirst('type')
        if client_type == '0': # client login
            return self._responseInvalidParam()
        elif client_type == '1': # web login
            return self._webgetcompany(params,paths)         
        return self._responseInvalidParam()



    def applysub(self, params):
        '''
        login application entrance, two types:
        1. client login
        2. web login
        '''
        #params = parse(None, environ)         
        client_type = params.getfirst('type')
        if client_type == '0': # client login
            return self._responseInvalidParam()
        elif client_type == '1': # web login
            return self._webapplysub(params)         
        return self._responseInvalidParam()


    def _clientLogin(self, request_params):
        '''
            负责客户端的登陆操作
        '''
        try:            
            cdkey = request_params.getfirst('cdkey')
            uuid = request_params.getfirst('uuid')
            username = request_params.getfirst('username')
            pwd = request_params.getfirst('pwd')           
                    
            if cdkey == None or uuid == None or username == None or pwd == None:
                self.debug.e("LoginService._clientLogin: param incomplete, cdkey:%s, uuid:%s, username:%s, pwd:%s"
                             % (cdkey, uuid, username, pwd))
                return self._responseError(-1,"param incomplete")

            dbsession =self._returndbsession()
            
            #check cdkey mapping
            dbmap = CdkeyManager.getCompanyShopIdPair(cdkey, dbsession)
            if dbmap == None:
                self.debug.e("LoginService._clientLogin: no such cdkey:%s" % cdkey)
                return self._responseError(103, "cdkey not exist")
        
            if CdkeyManager.isValide(cdkey, uuid, dbsession) is False:
                #response cdkey invalid, login failed            
                self.debug.e("LoginService._clientLogin: cdkey illegal, cdkey:%s" % cdkey)    
                return self._responseError(103, "cdkey invalid")
            #login
            company_id = dbmap[0]
            odno_id = dbmap[2]
            
            return self._login(company_id, username, pwd,odno_id)
        except Exception,e:
            self.debug.d("LoginService._clientLogin, Exception:%s" % e)
            return self._responseError(-1,"unknown exception:%s" % e)
          

    def _webLogin(self, request_params):
        '''
                负责web端的登陆操作
        '''        
        company_id = request_params.getfirst('company_id') 
        username = request_params.getfirst('username')
        pwd = request_params.getfirst('pwd')
        
        if company_id == None or username == None or pwd == None:
            self.debug.e("LoginService._webLogin, invalid param, company_id:%s, username:%s, pwd:%s" 
                         % (company_id, username, pwd))
            return self._responseInvalidParam()

        dbsession=self._returndbsession()      
        intcomp=LoginSessionManager.isValidCompanyid(company_id,dbsession)
        if intcomp == False:     
            self.debug.e("LoginService._webLogin, invalid company id:%s" % company_id)  
            return self._responseError(-1,"no company idwg")
        
        odno_id = 0;
          
        return self._login(company_id, username, pwd, odno_id)          
    
    
    
    def _getshopx(self,company_id,dbsession,request_params):
        danqian_id = request_params.getfirst('danqian_id')    
        username = request_params.getfirst('username')         
        token = request_params.getfirst('token')
 
        if danqian_id == None or token == None or username==None or company_id==None:
            return self._responseInvalidParam()
        
        #核实企业ID是否存在
        dbsession = self._returndbsession()
        intcomp=LoginSessionManager.isValidCompanyid(danqian_id, dbsession)
        if intcomp== False:
            self.debug.e("LoginService._getshopx: no such company id:%s" % company_id)
            return self._responseError(-1, 'no company id ')
        
        intcomp = LoginSessionManager.isValidSession(danqian_id, username, token, dbsession)        
        if intcomp==False:
            response_params = {}
            response_params['ret'] =107
            response_params['msg'] = 'session expired'            
            return self._response(json.dumps(response_params))

        Shop.doMapping(company_id)
        shops = dbsession.query(Shop).filter(Shop.id >=0)
        dbsession.commit()
        
        response_paramsARRAY = []   
        response_params={}
        response_params['ret'] =0
        response_params['msg'] = 'success'
     
        for row in shops:
            response_paramsb = {}
            response_paramsb["name"]=row.name
            response_paramsb["address"]=row.address
            response_paramsb["contact"]=row.contact
            response_paramsb["phone"]=row.phone
            response_paramsb["fax"]=row.fax
            response_paramsb["email"]=row.email       
            response_paramsb["id"]=row.id   
            response_paramsb["note"]=row.note                   
            response_paramsb["state"]=row.state                                          
            strtemp=json.dumps(response_paramsb)
            response_paramsARRAY.append(strtemp)  
        
        
        response_params['data']=response_paramsARRAY    
        return self._response(json.dumps(response_params))  
          
 
        
    
    def _webgetcompany(self, request_params,paths):
        '''
        负责web端的登陆操作
        '''        
        dbsession = self._returndbsession()
        company_id = request_params.getfirst('company_id')
        if paths[1]=="shopsh":
            return self._getshopx(company_id,dbsession,request_params)
        else:
            self.debug.e("LoginService._webgetcompany invalid path:%s" % repr(paths))
            return self._responseInvalidParam()
        
        company_id = request_params.getfirst('company_id')
        username = request_params.getfirst('username')         
        token = request_params.getfirst('token')
 
        if company_id == None or token == None:
            self.debug.e("LoginService._webgetcompany invalid param, company_id:%s, token:%s" 
                         % (company_id, token))
            return self._responseInvalidParam()
        
        #核实企业ID是否存在
        intcomp=LoginSessionManager.isValidCompanyid(company_id, dbsession)
        if intcomp== False:
            self.debug.e("LoginService._webgetcompany no such company_id:%s" % company_id)                    
            return self._responseError(-1, 'no company id')
        
        #检查TOKEN是否过期
        intcomp = LoginSessionManager.isValidSession(company_id, username, token, dbsession)        
        if intcomp==False:
            return self._responseError(107, 'TOKEN expired')
                    
        dbsessionsec =self._returndbsession()
        if paths[1]=="get":#集团公司登陆获取自己的信息
            company=dbsessionsec.query(Company).filter(Company.id == int(company_id))
        elif paths[1]=="sh":#艾云登陆，获取所有审核和未审核的公司信息            
            company=dbsessionsec.query(Company).filter(Company.id >=0)
        dbsessionsec.commit()
        self.debug.d("DDD:%s " % repr(company))
        response_paramsARRAY = []   
        response_params={}
        response_params['ret'] =0
        response_params['msg'] = 'success'
     
        
        for row in company:
            response_paramsb = {}
            response_paramsb["name"]=row.name
            response_paramsb["address"]=row.address
            response_paramsb["contact"]=row.contact
            response_paramsb["phone"]=row.phone
            response_paramsb["fax"]=row.fax
            response_paramsb["email"]=row.email       
            response_paramsb["id"]=row.id       
            response_paramsb["state"]=row.state                                          
            strtemp=json.dumps(response_paramsb)
            response_paramsARRAY.append(strtemp)     
        
        response_params['data']=response_paramsARRAY; 
        #response_paramsARRAY.append(response_params)
        return self._response(json.dumps(response_params))
                    
                    
                                                
    def _webapplysub(self, request_params):
        '''
            负责web端的申请服务
        '''        
        name = request_params.getfirst('name')
        address = request_params.getfirst('address')         
        yyzz = request_params.getfirst('yyzz')
        contact = request_params.getfirst('contact')
        phone = request_params.getfirst('phone')
        jytype = request_params.getfirst('jytype')
        jyguimo = request_params.getfirst('jyguimo')    
        email= request_params.getfirst('email')          
        if name == None or address == None or yyzz== None or contact==None or phone==None or jytype==None or jyguimo==None :
            return self._responseInvalidParam()
         
        #核实企业ID是否存在
        dbsession =self._returndbsession()
        intcomp=LoginSessionManager.HasApplyed(name,yyzz,contact,phone,dbsession)
        if intcomp== True:
            self.debug.e("LoginService._webapplysub: already exist, name:%s, address:%s" % (name, address))
            return self._responseError(-1,"already exist")
                         
        tempuuid=uuid.uuid4()
        company =Company()      
        company.name=name
        company.address=address
        company.contact=contact
        company.phone=phone
        company.jytype=jytype
        company.email=email
        company.jyguimo=jyguimo
        company.yyzz=yyzz
        company.uuid=tempuuid
        dbsession.add(company)
        dbsession.commit()
        
        companyb=dbsession.query(Company).filter(Company.uuid == tempuuid)
        dbsession.commit()
        response_paramsARRAY = []   
        for row in companyb:
            response_paramsb = {}
            response_paramsb["ret"]=0
            response_paramsb["msg"]="申请已经提交，企业ID：%d "  % row.id
            strtemp=json.dumps(response_paramsb)
            response_paramsARRAY.append(strtemp)      
        #response_paramsARRAY.append(response_params)
        return self._response(json.dumps(response_paramsARRAY))
                    

                            
    def _getUserRights(self, company_id, user_id, dbsession):
        
        UserRight.doMapping(company_id)
        
        rights = dbsession.query(UserRight).filter(UserRight.user_id == user_id)
        dbsession.commit()
        
        right_names = []
       
        for right in rights:
            response_paramsb={}
            response_paramsb["name"]=right.right_name
            rightsyuanshi=dbsession.query(Rights).filter(Rights.name == right.right_name)
            dbsession.commit()
            rightsyuanshi.first()
            if rightsyuanshi.count()==0:
                response_paramsb["note"]=right.right_name
            else:
                response_paramsb["note"]=rightsyuanshi[0].note
        
            strtemp=json.dumps(response_paramsb)
            right_names.append(strtemp)
                       
        return right_names
    
    def _login(self, company_id, username, pwd,odno_id):
        '''
            real login
        ''' 
        dbsession=self._returndbsession()
        res = LoginSessionManager.login(company_id, username, pwd, dbsession)
              
        response_params={}
        response_params["ret"]=0
        response_params["msg"]="success"
         
        if res[0] == 0:
            response_params['token'] = res[1]
            user_id = res[2]
            shop_id = res[3]
            user_name=res[4]
            right_level=res[5]
            realname=res[6]
        elif res[0] == -1 or res[0] == -2 or res[0] == -3:
            dbsession.close()   
            return self._responseError(-1, res[1])
        
        #get user rights
        rights = self._getUserRights(company_id, user_id, dbsession)
        company_name=self._getcompanyname(company_id, dbsession)
        shop_name=self._getshopname(company_id, shop_id, dbsession)
                        
        response_params['ret'] = 0
        response_params['rights'] = rights
        response_params['userid'] = user_id  
        response_params['username'] = user_name  
        response_params['company_id'] = company_id
        response_params['odno_id']=odno_id        
        response_params['shop_id'] = shop_id
        response_params['right_level'] = right_level
        response_params['realname'] = realname
        response_params['company_name'] = company_name
        response_params['shop_name'] = shop_name
        response_params['serverdatetime']=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")  
         
        strtemp=json.dumps(response_params)    
        self.debug.d("LoginService._login: user %s login ok" % user_name)
        return self._response(strtemp)         
    

    def _getcompanyname(self, company_id,dbsession):
 
        company = dbsession.query(Company).filter(Company.id==company_id)        
        dbsession.commit()
        
        if company.count()==0:
            return company_id
        return company.first().name
        
        

    def _getshopname(self, company_id,shop_id,dbsession):
        Shop.doMapping(company_id)
        shop = dbsession.query(Shop).filter(Shop.id==shop_id)        
        dbsession.commit()
        
        if shop.count()==0:
            return shop_id
        
        return shop.first().name
        
        
    def _getCompanydata(self, company_id, username, pwd, dbsession):
        '''
            get company data
        '''

        res = LoginSessionManager.login(company_id, username, pwd, dbsession)
        response_params = {}
        if res[0] == 0:
            response_params['token'] = res[1]
            user_id = res[2]
            shop_id = res[3]
        elif res[0] == -1 or res[0] == -2 or res[0] == -3:
            response_params['ret'] = -1
            response_params['msg'] = res[1]
            return self._response(json.dumps(response_params))
        
        #get user rights
        rights = self._getUserRights(company_id, user_id, dbsession)
                        
        response_params['ret'] = 0
        response_params['rights'] = rights
        response_params['user_id'] = user_id  
        response_params['company_id'] = company_id
        response_params['shop_id'] = shop_id      
        return self._response(json.dumps(response_params))         
    

     
    
    
if __name__ == '__main__':
    def start_response(a, b):
        pass
    
    loginservice = LoginService(start_response)
    #params = {'type':[0], 'username':['wxr'], 'pwd':['1234'], 'cdkey':['OOS21-2EYR3-Y9OSN-GYU3O'], 'uuid':['WXUP-YUMQ-MOPY']}
    env = {} 
    env['QUERY_STRING'] = 'type=0&username=wxr&pwd=1234&cdkey=OOS21-2EYR3-Y9OSN-GYU3O&uuid=WXUP-YUMQ-MOPY'
    params = cgi.FieldStorage(environ = env) 
 
    loginservice.application(params)  
        
         
if __name__ == "__main__":
    loginService = LoginService()
    loginService.application(None, None)
        
        